package cn.itcast.service.impl;

import cn.itcast.dao.ProvinceDao;
import cn.itcast.dao.impl.ProvinceDaoImpl;
import cn.itcast.domain.Province;
import cn.itcast.jedis.utils.JedisPoolUtils;
import cn.itcast.service.ProvinceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService {
    //声明dao
    private ProvinceDao provinceDao = new ProvinceDaoImpl();

    @Override
    public List<Province> findAll() {
        List<Province> list = provinceDao.findAll();

        return list;
    }

    //使用Redis缓存数据
    @Override
    public String findAllJson() {
        //1.先从Redis中查询province数据
        //2.有数据就从Redis中获取  没有数据就访问数据库并将数据放到到Redis中存储
        //1.1获取Redis连接
        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");

        //2.有数据就从Redis中获取  没有数据就访问数据库并将数据放到到Redis中存储
        if (province_json == null || province_json.length() == 0) {
            List<Province> list = provinceDao.findAll();
            //将list集合序列化为json
            ObjectMapper objectMapper=new ObjectMapper();
            try {
                province_json = objectMapper.writeValueAsString(list);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            jedis.set("province", province_json);
            jedis.close();

        }
        return province_json;
    }
}
